<template>
    <div class="main mt-4 w-full">
        <div class="flex items-center justify-between w-full mb-2">
            <span>
                {{ props.index + 1 }}、
            </span>
            <el-button v-if="props.index > 0" @click="onDelItem" :icon="Delete" size="small" type="danger" class="ml-2" />
        </div>
        <el-form :model="formData" ref="formRef">
            <el-form-item label="所属分类" prop="categoryId" required>
                <el-select 
                v-model="formData.categoryId" 
                @change="onChange" 
                filterable
                placeholder="选择或添加类型"
                allow-create
                >
                    <el-option 
                    v-for="item in props.categoryList" 
                    :key="item.id"
                    :value="item.id"
                    :label="item.categoryName" 
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="难度" prop="difficulty" class="mt-4">
                <el-input-number @change="onChange" :min="1" v-model="formData.difficulty" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="分值" prop="score" class="mt-4">
                <el-input-number @change="onChange" :min="1" v-model="formData.score" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="数量" prop="num" class="mt-4">
                <el-input-number @change="onChange" :min="1" v-model="formData.num" placeholder="请输入" />
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus';
import {  reactive, ref, watch } from 'vue';
import { Delete } from '@element-plus/icons-vue';

const formRef = ref<FormInstance>();

const emit = defineEmits(['update:modelValue', 'change', 'del']);

const props = defineProps<{
    categoryList: any[];
    modelValue: any;
    index: number;
}>();

const formData = reactive<any>({
    categoryId: '',
    difficulty: 1,
    num: 1,
    score: 3
});

const onDelItem = () => {
    emit('del', props.index);
};

const onChange = () => {
    emit('update:modelValue', {...formData});
    emit('change', {...formData});
};

watch(
    props.modelValue,
    modelValue => {
        Object.keys(formData).forEach(key => {
            formData[key] = modelValue[key];
        });
    },
    {
        deep: true
    }
);

defineExpose({
    validate: () => formRef.value?.validate(),
});
</script>